package com.ionafan2.iaccepteuromaidan;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class VotingActivity extends Activity {

    private String deviseId;

    private RequestPostTask votingTask = null;
    private View mVotingWrapperView;
    private View mVotingStatusView;
    private TextView mVotingStatusMessage;
    private SharedPreferences preferences;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.pull_in_from_right, R.anim.hold);
        setContentView(R.layout.activity_voting);

        deviseId = Utils.getDeviceId(this);
        preferences = getSharedPreferences("auth", MODE_APPEND);

        mVotingWrapperView = findViewById(R.id.vote_wrapper);
        mVotingStatusView = findViewById(R.id.vote_wrapper_status);
        mVotingStatusMessage = (TextView) findViewById(R.id.voting_status_message);

        findViewById(R.id.button_vote).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doVote();
            }
        });
    }

    private void doVote() {

        mVotingStatusMessage.setText(R.string.voting_progress_in);
        showProgress(true);

        ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

        nameValuePair.add(new BasicNameValuePair("token", preferences.getString(Const.AUTH_TOKEN, "")));
        nameValuePair.add(new BasicNameValuePair("device_id", deviseId));

        votingTask = new RequestPostTask(nameValuePair).setOnRequestTaskListener(new PostTaskListener());
        votingTask.execute(Settings.SIGNUP_VOTING_URL);
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {

        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mVotingStatusView.setVisibility(View.VISIBLE);
            mVotingStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mVotingStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mVotingWrapperView.setVisibility(View.VISIBLE);
            mVotingWrapperView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mVotingWrapperView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mVotingStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mVotingWrapperView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    private class PostTaskListener implements RequestPostTaskListener {

        @Override
        public void onDataLoaded(String responseJsonString) {
            if (responseJsonString != null && responseJsonString.length() != 0) {

                try {
                    JSONObject responseObject = new JSONObject(responseJsonString);
                    JSend jSend = new JSend();

                    if (jSend.isValid(responseObject)) {
                        if (responseObject.get(JSend.STATUS).equals(JSend.SUCCESS)) {
                            votingTask = null;
                            showProgress(false);
                            Intent intent = new Intent(VotingActivity.this, FinishActivity.class);
                            startActivity(intent);
                        } else if (responseObject.get(JSend.STATUS).equals(JSend.FAIL)) {
                            votingTask = null;
                            showProgress(false);
                            Toast.makeText(VotingActivity.this, responseObject.optString(JSend.DATA), Toast.LENGTH_LONG).show();
                        } else if (responseObject.get(JSend.STATUS).equals(JSend.ERROR)) {
                            votingTask = null;
                            showProgress(false);
                            Toast.makeText(VotingActivity.this, responseObject.optString(JSend.MESSAGE), Toast.LENGTH_LONG).show();
                        }
                    } else {
                        votingTask = null;
                        showProgress(false);
                        Toast.makeText(VotingActivity.this, "JSend is invalid!", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                votingTask = null;
                showProgress(false);
                Toast.makeText(VotingActivity.this, "Empty response.", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancelled() {
            votingTask = null;
            showProgress(false);
        }
    }
}